<template>
  <div>
    <h2>個人管理系統</h2><br>
    <el-form :model="numberValidateForm" ref="numberValidateForm" label-width="100px" class="demo-ruleForm">
      <el-form-item
          label="新用戶名"
          prop="newUserName"
          :rules="[
      { required: true, message: '用戶名不能为空!'},
      { type: 'string', message: '用戶名非法!'}
    ]">
        <el-input v-model="numberValidateForm.newUserName" name="newUserName" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('numberValidateForm')">提交</el-button>
        <el-button @click="resetForm('numberValidateForm')">重置</el-button>
      </el-form-item>
    </el-form>
    <el-descriptions title="用户信息">
      <el-descriptions-item label="用户名">{{ currentUserInfo.username}}</el-descriptions-item>
      <el-descriptions-item label="手机号">{{ currentUserInfo.phoneNumber}} &nbsp <el-link type="primary" icon="el-icon-edit" href="UpdatePhoneNumber">修改手機</el-link><br></el-descriptions-item>
      <el-descriptions-item label="得分">{{ currentUserInfo.rangeScore}}</el-descriptions-item>
<!--      <el-descriptions-item label="頭像" :src="currentUserInfo.userIcon"></el-descriptions-item>-->
      <el-descriptions-item label="用戶身份备注">
        <el-tag size="small">
          <h2 v-if="currentUserInfo.permission ===0">管理員</h2>
          <h2 v-if="currentUserInfo.permission ===1">講師</h2>
          <h2 v-if="currentUserInfo.permission ===2">學生</h2>
        </el-tag>
      </el-descriptions-item>
    </el-descriptions>
<br>


    <el-row>
      <el-col ><div class="grid-content bg-purple-dark">
        <div>
          <el-avatar shape="square" :size="200" :src="currentSrc"></el-avatar>
        </div>
      </div></el-col>
    </el-row>
    <br>
    <div >
    <el-upload action="http://localhost:9191/userinfo/profilePhotoUpload" multiple list-type="picture-card" :data="fileData"  name="file"
               accept="image/jpeg,image/png,image/jpg" :on-preview="handlePictureCardPreview" :on-remove="handleRemove"
               :on-success="handleimg" >
      <el-icon>
        <Plus />
      </el-icon>
      <template #tip>
        <div class="el-upload__tip"  >只能上传jpg/png/jpeg文件，且单个不超过2M</div>
      </template>
    </el-upload>
    <el-dialog v-model="dialogVisible">
      <img w-full :src="imageUrl" alt="Preview Image" />
    </el-dialog>
</div>

  </div>
</template>

<script>
import Cookies from 'js-cookie'
import router from "@/router";
import Success from "@/components/Success";
export default {
  name: "Overview",
  data() {

    return {

      numberValidateForm: {
        newUserName: ''
      },


      src:"",
      imageUrl: '',
      dialogVisible: false,
      fileData: {   // 额外参数
        token: Cookies.get('user'),
        currentUserInfo: '',
        currentSrc:'',
      },
      currentSrc:'',
      currentUserInfo:'',
      username:'',

    }
  },
        methods:{
          submitForm(formName) {
            this.$refs[formName].validate((valid) => {
              if (valid) {
                // alert('submit!');

                 let config =this.numberValidateForm.newUserName
                let data={param:config,
                  token:this.token}
                alert(config)
                this.$axios.post("/userinfo/updateUserName",data)
                    .then(res => {
                  console.log(res);
                      let responseData = res.data;
                      console.log(responseData)
                      console.log("resData================="+JSON.stringify(responseData))
                      if (responseData.code === 200) {
                        console.log("...............................s")



                        this.$message({
                          message: responseData.msg,
                          type:"success",
                          duration:2000,
                        })

                        router.push("Success");
                      }

                })
              } else {
                console.log('error submit!!');
                return false;
              }
            });
          },
          resetForm(formName) {
            this.$refs[formName].resetFields();
          },





          initCurrentUser() {
            let usertoken  = Cookies.get('user');
            console.log("usertoken/////////////")
            console.log(usertoken)

            const config = {
                token:usertoken,
            }
            console.log("config////////////////////////////////////////////")
            console.log(config)
            this.$axios.post("/userinfo/analysis", config)
                .then(response => {
                  console.log(response)

                  let responseData = response.data;
                  console.log(responseData)


                  if (responseData.code === 200) {
                    let userdata = responseData.data;
                    console.log( "userdata---------------------------------")
                    console.log( userdata)

                    if (userdata) {
                      this.currentUserInfo = userdata;
                      this.currentSrc = userdata.userIcon;
                      console.log( "this.currentSrc-------------------------")
                      console.log( this.currentSrc)
                    }else {
                      this.$message({
                        message: responseData.msg,
                        type: "error",
                        duration: 2000,
                      })
                      this.logout();
                    }
                  } else {
                    this.$message({
                      message: "登录状态异常,请重新登录",
                      type: "error",
                      duration: 2000,
                    })
                    this.logout();
                  }
                  this.src = response.data.data.userIcon;
                })

          },
          handleRemove(img, fileList) {
            console.log(img, fileList);
          },
          handlePictureCardPreview(img) {
            //这里需要注意 用的img并不是file，因为接口文档给的是img，我们在upload中定义个name=“img”参数就可以了
            // 检查文件类型
            const isImage = img.raw.type.includes("image");
            if (!isImage) {
              this.$message.error("上传文件类型必须是图片!");
              return false
            }
            // 检查文件大小
            if (img.size > (2 * 1024 * 1024)) {
              this.$message.error(`上传文件大小不能超过10Mb`);
              this.$refs['refUpload'].handleRemove(img);
              return false;
            }
            // 检查文件数量
            if (fileList.length > 1) {
              this.$message.error(`上传文件最大数量为1`);
              this.$refs['refUpload'].handleRemove(img);
              return false;
            }
            this.ImageUrl = img.url;

            console.log(this.ImageUrl);
            this.dialogVisible = true;
          },
          handleimg(res, img, fileList) {
            console.log(img);
            console.log(fileList);
            if (res.code === 200) {
              this.url = res.data.file
              this.$message(`图片${img.name}上传成功`)
            } else {
              this.$message.error(`图片${img.name}上传失败`)
            }
          },

        },

        created() {
          this.initCurrentUser();

        }
}



</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>